package com.quan.common.base.exception;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BizException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(BizException.class);

	/**
	 * 数据库操作,插入数据异常
	 */
	public static final BizException DB_INSERT_EXCEPTION = new BizException(10040001, "数据库操作,插入数据异常");
	
	/**
	 * 数据库操作,修改数据异常
	 */
	public static final BizException DB_UPDATE_EXCEPTION = new BizException(10040002, "数据库操作,修改数据异常");

	/**
	 * 数据库操作,删除数据异常
	 */
	public static final BizException DB_DELETE_EXCEPTION = new BizException(10040002, "数据库操作,删除数据异常");

	/**
	 * 数据库操作,查询数据异常
	 */
	public static final BizException DB_SELECTONE_EXCEPTION = new BizException(10040003, "数据库操作,查询数据异常");

	/**
	 * 数据库操作,查询数据列表异常
	 */
	public static final BizException DB_LIST_EXCEPTION = new BizException(10040004, "数据库操作,查询数据列表异常");

	/**
	 * 异常信息
	 */
	protected String msg;

	/**
	 * 具体异常码
	 */
	protected int code;

	public BizException(int code, String msgFormat, Object... args) {
		super(String.format(msgFormat, args));
		this.code = code;
		this.msg = String.format(msgFormat, args);
	}

	public BizException(String msgFormat, Object... args) {
		super(String.format(msgFormat, args));
		this.msg = String.format(msgFormat, args);
	}

	public BizException logError(Exception e) {
		return errorMsg(e);
	}

	public BizException errorMsg(Exception e) {
		logger.error(this.msg + "\r\n" + ExceptionUtils.getMessage(e));
		return new BizException(this.msg + " - " + ExceptionUtils.getRootCauseMessage(e));
	}

	public BizException print() {
		logger.info("==>BizException, code:" + this.code + ", msg:" + this.msg);
		return this;
	}

	public BizException() {
		super();
	}

	public BizException(String message, Throwable cause) {
		super(message, cause);
	}

	public BizException(String message) {
		super(message);
	}

	public BizException(Throwable cause) {
		super(cause);
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	
}
